import React, { useMemo } from 'react';
import { Form, Row, Col, Space, Button } from 'antd';
import P from 'prop-types';

import S from './styles.less';

/**
 * 该组件的子元素一定是 Form.Item
 * 可以直接复用 Form 组件的属性
 * @param {*} props
 */
export default function FormWrapper(props) {
  const { children, submitLoading, ...formProps } = props;
  const [form] = Form.useForm();

  const submitColProps = useMemo(() => {
    if (children) {
      const childLength = React.Children.count(children) || 0;
      return {
        xs: { span: 24, offset: 0 },
        sm: { span: 24, offset: 0 },
        md: { span: 12, offset: [12, 0][(childLength % 2).toFixed(0)] },
        lg: { span: 12, offset: [12, 0][(childLength % 2).toFixed(0)] },
        xl: { span: 8, offset: [16, 8, 0][(childLength % 3).toFixed(0)] },
        xxl: { span: 6, offset: [18, 12, 6, 0][(childLength % 4).toFixed(0)] },
      };
    }
    return {};
  }, [children]);

  return (
    <div className={S.query}>
      <Form
        labelCol={{ span: 8 }}
        wrapperCol={{ span: 16 }}
        name="query"
        {...formProps}
        form={form}
      >
        <Row style={{ width: '100%' }} align="middle" gutter={[0, 0]}>
          {/* 渲染其他表单 */}
          {children &&
            React.Children.map(children, child => (
              <Col xs={24} sm={24} md={12} lg={12} xl={8} xxl={6}>
                {child}
              </Col>
            ))}

          <Col {...submitColProps}>
            <Form.Item
              wrapperCol={{ span: 24 }}
              style={{ textAlign: 'right', marginRight: 0 }}
            >
              <Space>
                <Button
                  type="primary"
                  htmlType="submit"
                  loading={submitLoading}
                >
                  查询
                </Button>
                <Button type="default" onClick={() => form.resetFields()}>
                  重置
                </Button>
              </Space>
            </Form.Item>
          </Col>
        </Row>
      </Form>
    </div>
  );
}

FormWrapper.defaultProps = {
  submitLoading: false, // 提交按钮的loading状态
};

FormWrapper.propTypes = {
  submitLoading: P.bool,
};
